import { useEffect, useState } from 'react';
import { get } from '../services/api';
import CommonTable from '../components/CommonTable';
import StudentGradeModal from '../components/StudentGradeModal';
import { Button, Space } from 'antd';
import { FileTextOutlined } from '@ant-design/icons';

function StudentsPage() {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [gradeModal, setGradeModal] = useState({
    visible: false,
    studentInfo: null
  });

  useEffect(() => {
    setLoading(true);
    get('students')
      .then(response => {
        setStudents(response);
        setLoading(false);
      })
      .catch(error => {
        console.error('获取学生数据失败:', error);
        setLoading(false);
      });
  }, []);

  const handleViewGrades = (student) => {
    setGradeModal({
      visible: true,
      studentInfo: student
    });
  };

  const handleGradeModalClose = () => {
    setGradeModal({
      visible: false,
      studentInfo: null
    });
  };

  const columns = [
    {
      title: '学号',
      dataIndex: 'student_id',
      key: 'student_id',
      sorter: (a, b) => a.student_id.toString().localeCompare(b.student_id.toString()),
      width: '30%',
    },
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      sorter: (a, b) => a.student_name.localeCompare(b.student_name),
      width: '40%',
    },
    {
      title: '操作',
      key: 'action',
      width: '30%',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<FileTextOutlined />}
            onClick={() => handleViewGrades(record)}
            size="small"
          >
            查看成绩
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <CommonTable
        title="学生管理"
        columns={columns}
        dataSource={students}
        loading={loading}
        rowKey="student_id"
        searchFields={['student_id', 'student_name']}
      />
      
      <StudentGradeModal
        visible={gradeModal.visible}
        onClose={handleGradeModalClose}
        studentInfo={gradeModal.studentInfo}
      />
    </>
  );
}

export default StudentsPage;